package com.hbue.water.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.hbue.water.common.CommonResult;
import com.hbue.water.common.ResponseCode;
import com.hbue.water.entity.Worker;
import com.hbue.water.service.WorkerService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author yushu
 * @date 2021/12/27
 * @apiNate
 */
@RestController
@RequestMapping("/worker")
@Slf4j
@ApiModel("送水工管理Controller")
public class WorkerController {

    @Autowired
    private WorkerService workerService;

    /**
     * 从yml配置文件中读取服务器存放上传图像的路径
     */
    @Value("${location}")
    private String location;

    @ApiOperation("分页查询所有送水工信息")
    @GetMapping("/listWorkerPage/{pageNum}/{pageSize}")
    public CommonResult<PageInfo> listWorker(
            @ApiParam(name="pageNum",value="当前页",required = true)
            @PathVariable("pageNum") Integer pageNum,
            @ApiParam(name = "pageSize", value = "每页数据量", required = true)
            @PathVariable("pageSize") Integer pageSize){
        PageInfo<Worker> pageInfo = workerService.listWorker(pageNum,pageSize);
        return new CommonResult<>(ResponseCode.RESPONSE_SUCCESS,"success",pageInfo);
    }

    @ApiOperation("展示所有送水工信息")
    @GetMapping("/listWorker")
    public CommonResult<List<Worker>> listWorker() {
        List<Worker> workerList = workerService.list();
        return new CommonResult<>(ResponseCode.RESPONSE_SUCCESS, "ok", workerList);
    }

    /**
     * 处理浏览器上传文件的逻辑
     *
     * @param worker
     * @param file
     */
    private boolean uploadFile(Worker worker, MultipartFile file) {
        String clientFileName = file.getOriginalFilename();
        // 条件成立：表示前端上传了图片，处理上传图片的操作。
        if (StrUtil.isNotEmpty(clientFileName)) {
            int index = clientFileName.lastIndexOf(".");
            // 获取上传文件的后缀名称。例如:  .png
            String suffix = clientFileName.substring(index);
            // 系统当前时间作为上传文件的前缀. 例如： 15574565463564
            long prefix = System.nanoTime();
            // 拼接前缀和后缀
            // newFileName存储新的上传文件名。例如：15574565463564.png
            String newFileName = prefix + suffix;
            // 创建服务器存储浏览器上传文件路径的File对象
            File serverFilePath = new File(location);
            // 条件成立：表示路径在磁盘中不存在，需要手动创建该路径
            if (!serverFilePath.exists()) {
                serverFilePath.mkdirs();
            }

            File uploadPath = new File(serverFilePath, newFileName);
            deleteFile(worker.getWorkerImage());
            try {
                file.transferTo(uploadPath);
            } catch (IOException e) {
                log.info("upload file exception ", e);
                e.printStackTrace();
                return false;
            }
            // 将上传的文件名称注入到worker对象中
            worker.setWorkerImage(newFileName);
        }
        return true;
    }

    private void deleteFile(String imageName) {
        if (imageName != null) {
            String path = location + '/' + imageName;
            log.info("path = " + path);
            boolean flag = FileSystemUtils.deleteRecursively(new File(path));
            log.info("flag = " + flag);
        }
    }


    /**
     * 添加送水工，图片上传
     *
     * @param worker 送水工信息
     * @param file   上传的图片信息
     * @return 后端将添加送水工的结果返回给前端  success表示上传成功
     */
    @ApiOperation("添加送水工，图片上传")
    @PostMapping("/saveWorker")
    public CommonResult saveWorker(
            @ApiParam(name = "worker", value = "送水工信息", required = true) Worker worker,
            @RequestParam("file") MultipartFile file) {
        // 上传图片
        if (!this.uploadFile(worker, file)) {
            return new CommonResult(ResponseCode.RESPONSE_FAIL, "fail");
        }
        // 添加送水工信息
        boolean rows = workerService.save(worker);
        if (rows) {
            return new CommonResult(ResponseCode.RESPONSE_SUCCESS, "success");
        } else {
            return new CommonResult(ResponseCode.RESPONSE_FAIL, "fail");
        }
    }

    @ApiOperation("根据送水工id删除送水工信息")
    @GetMapping("/delWorker/{wid}")
    public CommonResult<Boolean> deleteWorker(
            @ApiParam(name = "wid", value = "送水工id", required = true)
            @PathVariable("wid") Integer wid) {
        log.info("delete Worker wid = " + wid);
        Worker worker = workerService.getById(wid);
        deleteFile(worker.getWorkerImage());
        boolean flag = workerService.removeById(wid);
        return new CommonResult<>(ResponseCode.RESPONSE_SUCCESS, "ok", flag);
    }

    @ApiOperation("根据送水工id查询送水工信息，数据回显")
    @GetMapping("/getWorkerById/{wid}")
    public CommonResult<Worker> getWorkerById(
            @ApiParam(name = "wid", value = "送水工id", required = true)
            @PathVariable("wid") Integer wid) {
        Worker worker = workerService.getById(wid);
        if (null == worker) {
            return new CommonResult<>(ResponseCode.RESPONSE_FAIL, "null", null);
        } else {
            return new CommonResult<>(ResponseCode.RESPONSE_SUCCESS, "ok", worker);
        }
    }

    @ApiOperation("修改送水工信息")
    @PostMapping("/updateWorker")
    public CommonResult updateWorker(
            @ApiParam(name = "worker", value = "前端采集的送水工信息", required = true) Worker worker,
            @RequestParam("file") MultipartFile file) {
        // 上传图片
        if (!this.uploadFile(worker, file)) {
            return new CommonResult(ResponseCode.RESPONSE_FAIL, "fail");
        }
        boolean flag = workerService.updateById(worker);
        return new CommonResult<>(ResponseCode.RESPONSE_SUCCESS, "ok");
    }

    @ApiOperation("根据搜索条件查找送水工信息")
    @GetMapping("/searchWorker/{pageNum}/{pageSize}/{searchCondition}")
    public CommonResult<PageInfo> searchWorker(
            @ApiParam(name="pageNum",value="当前页",required = true)
            @PathVariable("pageNum") Integer pageNum,
            @ApiParam(name = "pageSize", value = "每页数据量", required = true)
            @PathVariable("pageSize") Integer pageSize,
            @ApiParam(name = "searchCondition", value = "搜索条件", required = true)
            @PathVariable("searchCondition") String searchCondition) {
        log.info("search searchCondition = " + searchCondition);
        PageInfo<Worker> pageInfo = workerService.searchCustomer(pageNum, pageSize, searchCondition);
        return new CommonResult<>(ResponseCode.RESPONSE_SUCCESS, "ok", pageInfo);
    }

    @ApiOperation("处理前端调整工资请求")
    @PostMapping("/adjustSalary")
    public CommonResult<Integer> adjustSalary(
            @ApiParam(name = "wid", value = "送水工id", required = true)
            @RequestParam("wid") Integer wid,
            @ApiParam(name = "workerSalary", value = "调整后的工资", required = true)
            @RequestParam("workerSalary") Integer workerSalary) {
        log.info("adjustSalary workerId = " + wid + " workerSalary = " + workerSalary);
        Worker worker = new Worker();
        worker.setWid(wid);
        worker.setWorkerSalary(workerSalary);
        int rows = workerService.adjustSalary(worker);
        return new CommonResult<>(ResponseCode.RESPONSE_SUCCESS, "ok", rows);
    }

}
